from flask import Blueprint, render_template, jsonify, request, send_file
import pandas as pd
import numpy as np
from pathlib import Path
from accommodation_expense_2_analysis import main as analyze_accommodation
from io import BytesIO

# 创建蓝图
accommodation_2_bp = Blueprint('accommodation-2', __name__, url_prefix='/accommodation-2')

# 结果文件路径
RESULT_FILE = Path("data/alldata/住宿费超标分析结果(培训申请).xlsx")

@accommodation_2_bp.route('/')
def index():
    """渲染住宿费分析页面"""
    return render_template('pages/accommodation_expense2.html')

@accommodation_2_bp.route('/check-result-file')
def check_result_file():
    """检查结果文件是否存在"""
    return jsonify({'exists': RESULT_FILE.exists()})

@accommodation_2_bp.route('/generate-analysis', methods=['POST'])
def generate_analysis():
    """生成分析数据"""
    try:
        success = analyze_accommodation()
        return jsonify({'success': success})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@accommodation_2_bp.route('/get-data')
def get_data():
    """获取分析结果数据"""
    try:
        if not RESULT_FILE.exists():
            return jsonify({'success': False, 'error': '数据文件不存在'})
            
        # 读取Excel文件
        df = pd.read_excel(RESULT_FILE)
        
        # 处理特殊值（NaN, inf, -inf）
        df = df.replace({
            np.nan: None,
            np.inf: None,
            -np.inf: None
        })
        
        # 处理数值列，确保它们是可序列化的
        for col in df.select_dtypes(include=[np.number]).columns:
            df[col] = df[col].apply(lambda x: float(x) if pd.notnull(x) else None)
        
        # 转换为字典列表
        data = df.to_dict('records')
        
        return jsonify({
            'success': True,
            'data': data,
            'all_columns': df.columns.tolist()
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@accommodation_2_bp.route('/download-excel')
def download_excel():
    """下载住宿费超标分析结果"""
    try:
        if not RESULT_FILE.exists():
            return jsonify({
                'error': '分析结果文件不存在'
            }), 404

        # 读取Excel文件
        df = pd.read_excel(RESULT_FILE)
        
        # 获取选择的字段
        selected_fields = request.args.getlist('fields')
        
        # 如果指定了字段，只保留选择的字段
        if selected_fields:
            # 确保所有请求的字段都存在
            valid_fields = [field for field in selected_fields if field in df.columns]
            if not valid_fields:
                return jsonify({
                    'error': '没有找到有效的字段'
                }), 400
            df = df[valid_fields]

        # 如果数据为空，返回错误
        if df.empty:
            return jsonify({
                'error': '筛选后没有符合条件的数据'
            }), 400

        # 创建文件名
        filename = "住宿费超标分析结果（培训申请）.xlsx"
        
        # 使用BytesIO直接在内存中处理Excel文件
        excel_buffer = BytesIO()
        
        # 直接写入内存流
        with pd.ExcelWriter(excel_buffer, engine='openpyxl') as writer:
            df.to_excel(writer, index=False)
        
        # 将指针移到开始位置
        excel_buffer.seek(0)
        
        return send_file(
            excel_buffer,
            as_attachment=True,
            download_name=filename,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        )

    except Exception as e:
        return jsonify({
            'error': f'下载文件时出错: {str(e)}'
        }), 500
